<?php

namespace App\Controllers;

use App\Models\NewsModel;
use CodeIgniter\Exceptions\PageNotFoundException;

class News extends BaseController
{
    
    public function create()
    {
        helper('form');

        $data = $this->request->getPost(['title', 'body']);

        // Checks whether the submitted data passed the validation rules.
        if (! $this->validateData($data, [
            'title' => 'required|max_length[255]|min_length[3]',
            'body'  => 'required|max_length[5000]|min_length[10]',
        ])) {
            // The validation fails, so returns the form.
            return $this->new();
        }

        // Gets the validated data.
        $post = $this->validator->getValidated();

        $model = model(NewsModel::class);
        
        $model->save([
            'title' => $post['title'],
            'slug'  => url_title($post['title'], '-', true),
            'body'  => $post['body'],
        ]);
        
        return view('templates/header', ['title' => 'Create a news item'])
            . view('news/success')
            . view('templates/footer');
    }
    public function index()
    {
        $model = model(NewsModel::class);

        $data = [
            'news_list' => $model->getNews(),
            'title'     => 'xieyuhang s News archive',
        ];

        return view('templates/header', $data)
            . view('news/index')
            . view('templates/footer');
    }

    public function show(?string $slug = null)
    {
        $model = model(NewsModel::class);

        $data['news'] = $model->getNews($slug);

        if ($data['news'] === null) {
            throw new PageNotFoundException('Cannot find the news item: ' . $slug);
        }

        $data['title'] = $data['news']['title'];

        return view('templates/header', $data)
            . view('news/view')
            . view('templates/footer');
    }
    public function new()
    {
        helper('form');

        return view('templates/header', ['title' => 'Create a news item'])
            . view('news/create')
            . view('templates/footer');
    }
    public function delete($id = null)  
    {  
        // 加载模型  
        $model = new NewsModel();  
  
        // 检查是否提供了有效的 ID  
        if ($id == null || !$model->find($id)) {  
            return redirect()->to('news')->with('error', '无效的新闻条目 ID');  
        }  
  
        // 尝试删除新闻条目  
        if ($model->delete($id)) {  
            // 删除成功，设置成功消息  
            return view('news/deleted', [  
                'title' => '新闻条目已删除',  
                'message' => '您已成功删除了该新闻条目。'  
            ]);  
        } else {  
            // 删除失败，设置错误消息并重定向回新闻列表  
            return redirect()->to('news')->with('error', '删除新闻条目时出错。');  
        }  
    }  
    
}